<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: bootstrap-editable-css"/>
    <th:block th:include="include :: header('新建盘点单')"/>
    <th:block th:include="include :: layout-latest-css"/>
    <th:block th:include="include :: ztree-css"/>
</head>

<body class="gray-bg">
<div class="container-div">
    <div class="row">
        <div class="col-sm-12 search-collapse">
            <form id="formId">
                <div class="select-list">
                    <ul>

<!--                        <li>-->
<!--                            <label class="is-required">仓库：</label>-->
<!--                            <select id="warehouseId" name="warehouseId" th:with="type=${session.warehouse}">-->
<!--                                &lt;!&ndash;								<option   th:value="${session.warehouseId}" th:text="${@dict.getDictLabel('${session.warehouseId}')}"></option>&ndash;&gt;-->
<!--                                <option th:each="dict : ${type}" th:text="${dict.warehouseName}" th:value="${dict.warehouseId}"></option>-->
<!--                            </select>-->
<!--                        </li>-->

                        <li>
                            <label>仓库：</label>
                            <select name="warehouseId" th:with="type=${@dict.getType('is_house')}" required>
                                <!--<option value="">请选择</option>-->
                                <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
                            </select>
                        </li>

                        <li>
                            <label class="is-required">出库类型：</label>
                            <select id="outType" name="outType" required>
                                <option value="6">盘点出库</option>
                            </select>
                        </li>


                        <li>
                            <label>单据编号：</label>
                            <input type="text" id="stockoutId" name="stockoutId" placeholder="自动生成"
                                   readonly="readonly"/>
                        </li>
                        <li>
                            <label>开单日期：</label>
                            <input type="text" id="createDate" name="createDate"/>
                        </li>

                        <li>
                            <a id="save" class="btn btn-primary btn-rounded btn-sm" onclick="saveOutStock()"><i
                                    class="fa fa-search"></i>&nbsp;保存单据</a>
                            <a id="reset" class="btn btn-warning btn-rounded btn-sm" onclick="$.form.reset()"><i
                                    class="fa fa-refresh"></i>&nbsp;重置</a>
                            <!--</li>-->
                    </ul>
                </div>
            </form>
        </div>

        <div class="btn-group-sm" id="toolbar" role="group">
            <!--<a id="selectProduct" class="btn btn-success" onclick="selectProduct()">
                <i class="fa fa-plus"></i> 选择物资
            </a>-->
            <a id="selectTrayCode" class="btn btn-success" onclick="selectTrayCode()">
                <i class="fa fa-plus"></i> 选择托盘
            </a>
            <a id="continue" class="btn btn-success" onclick="newReceiptAgain()">
                <i class="fa fa-plus"></i> 继续建单
            </a>
            <a id="delete" class="btn btn-danger multiple disabled" onclick="deleteProduct()">
                <i class="fa fa-remove"></i> 删除物资
            </a>

        </div>
        <div class="col-sm-12 select-table table-striped">
            <table id="bootstrap-table"></table>
        </div>
    </div>
</div>
<th:block th:include="include :: footer"/>
<th:block th:include="include :: bootstrap-table-editable-js"/>
<th:block th:include="include :: layout-latest-js"/>
<th:block th:include="include :: ztree-js"/>
<script th:inline="javascript">

    var productStatus = [[${@dict.getType('product_status')}]];
    var prefix = ctx + "pandian";

    $(function () {
        var options = {
            createUrl: prefix + "/addSave",
            clickToSelect: true,
            height: $(window).height() / 1.5,
            contenteditable: true,
            modalName: "出库主单",
            editable: true,
            columns: [{
                checkbox: true,

            },
                {
                    field: 'onlyIdentity',
                    title: 'ID',
                    visible: false
                },

                {
                    field: 'productId',
                    title: '物资编码',
                    align: 'center'
                },
                {
                    field: 'kechaiQuantity',
                    title: '物资名称',
                    align: 'center'

                },
                {
                    field: 'price',
                    title: '物料状态',
                    align: 'center',
                    formatter: function (value, row, index) {
                        return $.table.selectDictLabel(productStatus, value);
                    }
                },
                {
                    field: 'lotNo',
                    title: '批号',
                    align: 'center'
                },
                {
                    field: 'entryid',
                    title: '供应商',
                    align: 'center'
                },{
                    field: 'unitName',
                    title: '生成时间',
                    align: 'center'
                },{
                    field: 'quantityX',
                    title: '重量',
                    align: 'center'
                },
                {
                    field: 'stockQuantity',
                    title: '库存数量',
                    align: 'center'
                }, {
                    field: 'erpStockoutId',
                    title: '暂存单号',
                    align: 'center'
                },

                {
                    field: 'quantity',
                    title: '出库数量',
                    visible: true,
                },   {
                    field: 'fid',
                    title: '托盘条码',
                    visible: true,
                },

            ],

        };
        $.table.init(options);
        createTime();
    });

    //日期框
    function createTime() {
        var _input = document.getElementById('createDate');

        var date = new Date();
        var seperator = "";
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentDate = year + seperator + month + seperator + strDate; //当前日期

        _input.value = currentDate; //赋值给input.value
    }

    //选择物资
    function selectProduct() {
        var outType=$("#outType").val()
        if(outType=="" || outType==null){
            $.modal.alertWarning("请先选择出库类型");
            return;
        }
        var options = {
            title: '选择物资信息',
            url: "/out/productAndStock",
            callBack: callbackProduct
        };
        $.modal.openOptions(options);

    }

    function callbackProduct(index, layero) {
        var orders = [];
        var obj = {};

        var Members = layero.find("iframe")[0].contentWindow.result();
        if (Members.length == 0) {
            $.modal.alertWarning("请至少选择一条记录");
            return;
        }
        var rows2= $('#bootstrap-table').bootstrapTable('getData');
        for(var i=0;i<rows2.length;i++){
            for(var j=0;j<Members.length;j++){
                if(rows2[i].onlyIdentity==Members[j].onlyIdentity){
                    $.modal.alertWarning("已存在该物资")
                    $.modal.close();
                    return;
                }
            }
        }
        console.log(Members + "members")
        // 这里已经拿到了Members，即子页面返回的表格勾选的内容
        orders.splice(0, orders.length);
        for (var i = 0; i < Members.length; i++) {
            obj.onlyIdentity = Members[i].onlyIdentity;
            obj.productId = Members[i].productId;
            obj.kechaiQuantity = Members[i].lineId;
            obj.stockQuantity = Members[i].quantity;
            obj.price = Members[i].productGuid;
            obj.lotNo = Members[i].lotNo;
            obj.entryid = Members[i].inClassName;
            obj.unitName = Members[i].printDate;
            obj.quantityX = Members[i].weight;
            obj.erpStockoutId = Members[i].inOrderNo;
            obj.quantity = Members[i].quantity;

            orders.push(obj)
            obj = {};
        }
        console.log(orders)
        $.modal.close(index);
        $.modal.closeLoading();

        for (var j = 0; j < orders.length; j++) {
            var dataTree2 = orders[j];
            $('#bootstrap-table').bootstrapTable('append', dataTree2);
        }
    }

    //选择托盘
    function selectTrayCode() {
        // var url = "/out/pandian/selectTrayCode";
        // $.modal.open("选择库存信息", url);
        var options = {
            title: '选择托盘信息',
            url: "/pandian/selectTray",
            callBack: callbackTray
        };
        $.modal.openOptions(options);
    }

    function callbackTray(index, layero) {
        var orders = [];
        var obj = {};

        var Members = layero.find("iframe")[0].contentWindow.result();
        if (Members.length == 0) {
            $.modal.alertWarning("请至少选择一条记录");
            return;
        }
        var rows2= $('#bootstrap-table').bootstrapTable('getData');
        for(var i=0;i<rows2.length;i++){
            for(var j=0;j<Members.length;j++){
                if(rows2[i].onlyIdentity==Members[j].stockId){
                    $.modal.alertWarning("已存在该物资")
                    $.modal.close();
                    return;
                }
            }
        }
        console.log(Members + "members")
        // 这里已经拿到了Members，即子页面返回的表格勾选的内容
        orders.splice(0, orders.length);
        for (var i = 0; i < Members.length; i++) {
            obj.onlyIdentity = Members[i].onlyIdentity;
            obj.productId = Members[i].productId;
            obj.kechaiQuantity = Members[i].lineId;
            obj.stockQuantity = Members[i].quantity;
            obj.price = Members[i].productGuid;
            obj.lotNo = Members[i].lotNo;
            obj.entryid = Members[i].inClassName;
            obj.unitName = Members[i].printDate;
            obj.quantityX = Members[i].weight;
            obj.erpStockoutId = Members[i].inOrderNo;
            obj.quantity = Members[i].quantity;
            obj.fid = Members[i].trayCode;
            orders.push(obj)
            obj = {};
        }

        console.log(orders)
        $.modal.close(index);
        $.modal.closeLoading();

        for (var j = 0; j < orders.length; j++) {
            var dataTree2 = orders[j];
            $('#bootstrap-table').bootstrapTable('append', dataTree2);

        }

    }

    //保存单据
    function saveOutStock() {

        var rows = $('#bootstrap-table').bootstrapTable('getData');
        if (rows.length == 0) {
            $.modal.alertWarning("请选择物资");
            return;
        }
        if ($.validate.form()) {
            var params = new Object();
            var o = {};
            var a = $("#formId").serializeArray();
            $.each(a, function () {
                if (o[this.name]) {
                    if (!o[this.name].push) {
                        o[this.name] = [o[this.name]];
                    }
                    o[this.name].push(this.value || '');
                } else {
                    o[this.name] = this.value || '';
                }
            });
            params.outStockout = o;
            params.outStockoutDetailList = $("#bootstrap-table").bootstrapTable("getData", false);

            var opt = new Object()

            opt.url = '/pandian/addSave';
            opt.data = JSON.stringify(params);
            ajaxRequestJsonBody(opt, onSaveSuccess);

            function ajaxRequestJsonBody(opt, callback) {

                $.ajax({
                    url: opt.url,
                    /**必须是POST方法**/
                    type: 'post',
                    /**必须制定请求的类型**/
                    contentType: 'application/json',
                    data: opt.data,
                    dataType: 'json',
                    success: function (result) {
                        if (result.code == "0") {
                            $.modal.alertSuccess(result.msg);
                        } else if (result.code == "301") {
                            $.modal.alertWarning(result.msg);
                        }  else {
                            $.modal.alertError(result.msg);
                        }
                        if (callback)
                            callback(result);
                    },
                    error: function (XMLHttpRequest, textStatus, error) {
                        DataTable.config.ajaxError(XMLHttpRequest, textStatus, error, "设置失败");
                    }
                });
            }

        }
    }

    //保存单据后的回调函数
    function onSaveSuccess(data) {
        if (data.code == web_status.SUCCESS) {
            $('#stockoutId').attr("value", data.data);
            $('#save').addClass('disabled'); // Disables visually
            $('#selectProduct').addClass('disabled'); // Disables visually
            $('#selectTrayCode').addClass('disabled'); // Disables visually
            $('#reset').addClass('disabled');
            $('#delete').addClass('disabled');

        }
    }

    //继续建单
    function newReceiptAgain() {
        window.location.reload();
        $.form.reset()
    }

    //删除物资
    function deleteProduct() {


        //获取选中行的内容
        var contents = $.map($("#bootstrap-table").bootstrapTable('getSelections'), function (row) {
            return row.onlyIdentity;
        });

        //前端删除数据
        $("#bootstrap-table").bootstrapTable('remove', {
            field: 'onlyIdentity',
            values: contents
        });


    }

</script>
</body>
</html>